package com.zzy.mccjt.core.interceptor;

import com.zzy.mccjt.exception.UnauthorizedException;
import com.zzy.mccjt.model.CurrentUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.zzy.mccjt.constant.RequestConstant.CURRENT_USER;
import static com.zzy.mccjt.constant.RequestConstant.FROM_GATEWAY;
import static com.zzy.mccjt.constant.RequestConstant.USER_FLAG;

/**
 * @program: mccjt-cloud
 * @description:
 * @author: zhouyang.zheng
 * @create: 2022-08-02 17:41
 **/
@Slf4j
public class InnerRequestInterceptor extends AbstractRequestInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        // 外部请求都会经过业务网关，经过网关时请求头都会带上x-from-gateway
        String userId = request.getHeader(CURRENT_USER);
        String userFlag = request.getHeader(USER_FLAG);
        String gateway = request.getHeader(FROM_GATEWAY);
        if (!StringUtils.isEmpty(gateway)) {
            throw new UnauthorizedException(HttpStatus.UNAUTHORIZED.value(), "UNAUTHORIZED");
        }
        if (!StringUtils.isEmpty(userId) && !StringUtils.isEmpty(userFlag)) {
            CurrentUser.set(Integer.parseInt(userFlag), Long.parseLong(userId));
        }

        handleTenantInfo(request, (HandlerMethod) handler);

        return true;
    }
}
